#!/bin/bash

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
LOG_FILE=${SCRIPT_DIR}/build-local-docker-image.log
ERROR=""
API_IMAGE_NAME="midjourney-proxy-api"
ADMIN_IMAGE_NAME="midjourney-proxy-admin"

function stop_and_remove_containers() {
    # Stop and remove the existing containers
    docker stop ${API_IMAGE_NAME} >/dev/null 2>&1
    docker rm ${API_IMAGE_NAME} >/dev/null 2>&1
    docker stop ${ADMIN_IMAGE_NAME} >/dev/null 2>&1
    docker rm ${ADMIN_IMAGE_NAME} >/dev/null 2>&1
}

function remove_images() {
    # Remove the existing images
    docker rmi ${API_IMAGE_NAME} >/dev/null 2>&1
    docker rmi ${ADMIN_IMAGE_NAME} >/dev/null 2>&1
}

function install_dependencies() {
    # Install all dependencies
    cd ${SCRIPT_DIR}
    pnpm install || ERROR="install_dependencies failed"
    pnpm run build || ERROR="build_dependencies failed"
}

function build_api_image() {
    # build API docker image
    echo "Info: Building API docker image..."
    docker build ../../ -f Dockerfile -t ${API_IMAGE_NAME} || ERROR="build_api_image failed"
}

function build_admin_image() {
    # build Admin docker image
    echo "Info: Building Admin docker image..."
    docker build ../../ -f Dockerfile.admin -t ${ADMIN_IMAGE_NAME} || ERROR="build_admin_image failed"
}

function start_containers() {
    # Create necessary directories
    mkdir -p uploads logs

    # Start API container
    echo "Info: Starting API container..."
    docker run -d -p 3000:3000 --name ${API_IMAGE_NAME} --restart unless-stopped \
        -e NODE_ENV=production \
        -e PORT=3000 \
        -e HOST=0.0.0.0 \
        -e TZ=Asia/Shanghai \
        -v $(pwd)/uploads:/app/apps/api/uploads \
        -v $(pwd)/logs:/app/apps/api/logs \
        ${API_IMAGE_NAME} || ERROR="start_api_container failed"

    # Start Admin container
    echo "Info: Starting Admin container..."
    docker run -d -p 4173:4173 --name ${ADMIN_IMAGE_NAME} --restart unless-stopped \
        -e NODE_ENV=production \
        -e PORT=4173 \
        -e TZ=Asia/Shanghai \
        ${ADMIN_IMAGE_NAME} || ERROR="start_admin_container failed"
}

function check_container_status() {
    echo "Info: Checking container status..."
    sleep 10

    # Check API container
    if docker ps | grep -q ${API_IMAGE_NAME}; then
        echo "✅ API container is running"
        docker logs --tail 5 ${API_IMAGE_NAME}
    else
        echo "❌ API container failed to start"
        docker logs ${API_IMAGE_NAME}
        ERROR="api_container_not_running"
    fi

    # Check Admin container
    if docker ps | grep -q ${ADMIN_IMAGE_NAME}; then
        echo "✅ Admin container is running"
        docker logs --tail 5 ${ADMIN_IMAGE_NAME}
    else
        echo "❌ Admin container failed to start"
        docker logs ${ADMIN_IMAGE_NAME}
        ERROR="admin_container_not_running"
    fi
}

function log_message() {
    if [[ ${ERROR} != "" ]];
    then
        >&2 echo "build failed"
        >&2 echo "ERROR: ${ERROR}"
        exit 1
    else
        echo "🎉 Docker images built and containers started successfully!"
        echo ""
        echo "📊 Container Status:"
        docker ps --filter "name=${API_IMAGE_NAME}|${ADMIN_IMAGE_NAME}" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
        echo ""
        echo "🌐 Services available at:"
        echo "  - API: http://localhost:3000"
        echo "  - Admin: http://localhost:4173"
        echo ""
        echo "📝 Useful commands:"
        echo "  - View logs: docker logs -f ${API_IMAGE_NAME} | docker logs -f ${ADMIN_IMAGE_NAME}"
        echo "  - Stop containers: docker stop ${API_IMAGE_NAME} ${ADMIN_IMAGE_NAME}"
        echo "  - Remove containers: docker rm ${API_IMAGE_NAME} ${ADMIN_IMAGE_NAME}"
    fi
}

echo "Info: Installing dependencies"
install_dependencies

if [[ ${ERROR} == "" ]]; then
    echo "Info: Stopping and removing existing containers and images"
    stop_and_remove_containers
    remove_images
fi

if [[ ${ERROR} == "" ]]; then
    echo "Info: Building docker images"
    build_api_image

    if [[ ${ERROR} == "" ]]; then
        build_admin_image
    fi
fi

if [[ ${ERROR} == "" ]]; then
    echo "Info: Starting containers"
    start_containers

    if [[ ${ERROR} == "" ]]; then
        check_container_status
    fi
fi

log_message
